<?php

namespace Phone\Controller;

use Common\Controller\PhoneController;
use Phone\Model\ExtensionModel;
use Phone\Model\GoodsModel;
use Phone\Model\MemberModel;
use Phone\Model\MemberYhqModel;
use Phone\Model\ExtensionOpenModel;
use Phone\Model\ExtensionGoodModel;


class ExtensionController extends PhoneController
{
    private $platform = '百宝库商城代理支付';

    public function __construct()
    {
        parent::__construct();
        $this->em = new ExtensionModel();
        $this->member_id = session('member_id');
        $this->mm = new MemberModel();
        if (!in_array(ACTION_NAME, array('index', 'login', 'share_add'))) {
            if (empty($this->member_id)) {
                return redirect('login?exu_code='.I('get.exu_code'));
            }
            if (!in_array(ACTION_NAME, array('payCheck', 'pay', 'checkPay'))) {
                $level = $this->mm->find($this->member_id)['ex_level'];
                if (empty($level)) {
                    return redirect('index');
                }
            }
        }
    }

    /**
     *  判断是否登录前置
     */
    public function _before_index()
    {
        if ($this->member_id) {
            $data_mm = $this->mm->find($this->member_id);
            if ($data_mm && $data_mm['ex_level']) {
                if ($data_mm['ex_yhj']) {
                    return redirect('profitIndex');
                }
                return redirect('pullCoupon');
            }
        }
    }


    /**
     *  招募代理人
     */
    public function index()
    {
        $data = array(
            'ex_show_img' => $this->em->get('ex_show_img'),            // 首页图
            'editorValue' => $this->em->get('editorValue'),            // 活动介绍
            'status' => empty($this->member_id) ? 2 : 1,               // 2: 跳登录    1: 调支付
            'u_code' => I('get.exu_code')                              // 父 code 码  (跳登录 || 调支付 都要带上)
        );

        $this->assign($data);
        $this->display();
    }

    /**
     *  注册
     */
    public function login()
    {
        if (IS_POST) {
            $post   = I('post.');
            if (session('phonecode') != $post['code'] OR session('register_phone') != $post['phone']) {
                echo 0; exit;
            }
            if($this->mm->where(array('phone' => $post['phone']))->find()) {
                return false;
            }
            $ex_uid = $this->mm->where(array('ex_invitation' => $post['exu_code']))->find()['member_id'];
            $member_id = $this->mm->register($post['phone'], rand_username() ,$post['password'], '' , $ex_uid);
            if ($member_id) {
                $this->mm->login($post['phone'], $post['password']);
                echo 1; exit;
            }
            echo 2; exit;
        }
        $data = array(
            'exu_code' => I('get.exu_code'),                              // 父 code 码
            'banner' => $this->em->get('ex_reg_img')                    // 首页图
        );
        $this->assign($data);
        $this->display();
    }



    /**
     *  我的邀请码
     */
    public function invitation()
    {
        $code = $this->mm->find($this->member_id)['ex_invitation'];

        $data = array(
            'code' => $code,                                                                        // 邀请码
            'code_url' => $this->getShareUrl($code),                                                // 邀请地址
            'money' => $this->em->get('ex_divide'),                                                 // 邀请金额
            'ex_share_info' => $this->em->get('ex_share_info'),                                     // 分享介绍
            'ex_share_img'  => $this->em->get('ex_share_img')                                       // 分享图
        );

        $this->assign($data);
        $this->display();
    }


    /**
     *  领取代金券前置
     */
    public function _before_pullCoupon()
    {
        $status = $this->mm->where(array('member_id' => $this->member_id))->getField('ex_yhj');
        if (!empty($status)) {
            return redirect('profitIndex');
        }
    }


    /**
     *  领取代金券
     */
    public function pullCoupon()
    {
        $start = time();
        $end   = time() + ($this->em->get('ex_coupon_time') * 60 * 60 * 24);

        if (IS_POST) {
            $ex_yhj = $this->mm->where(array('member_id' => $this->member_id))->getField('ex_yhj');
            if ($ex_yhj) {
                return false;
            }

            $mym = new MemberYhqModel();
            $data['member_id'] = $this->member_id;
            $data['youhui_code'] = time() . $this->member_id . rand(100, 999);
            $data['money'] = $this->em->get('ex_coupon');
            $data['cart_total'] = $this->em->get('ex_all_coupon');
            $data['begin_time'] = date('Y-m-d H:i:s', $start - 86400);
            $data['end_time'] = date('Y-m-d H:i:s', $end);
            $data['remark'] = '恭喜你成为代理人,发放优惠券';
            $data['is_use'] = 0;
            $data['use_money'] = 0;
            $data['create_time'] = date('Y-m-d H:i:s', $start);

            $this->mm->where(array('member_id' => $this->member_id))->save(array('ex_yhj' => 1));

            echo $mym->data($data)->add(); exit;
        }

        $data = array(
            'ex_register' => $this->em->get('ex_coupon'),             // 代金券面值
            'start' => date('Y.m.d H:i', $start),               // 开始时间
            'end' => date('Y.m.d H:i', $end)                   // 截止时间
        );
        $this->assign($data);
        $this->display();
    }


    /**
     *  账号管理前置
     */
    public function _before_profitIndex()
    {
        $status = $this->mm->where(array('member_id' => $this->member_id))->getField('ex_yhj');
        if (empty($status)) {
            return redirect('pullCoupon');
        }
    }


    /**
     *  账户管理
     */
    public function profitIndex()
    {
        $mm = new MemberModel();
        $obj = $mm->find($this->member_id);
        $ex_sub = $mm->where(array('ex_uid' => $obj['member_id']))->count();
        $good = $this->pullGoodDay();

        $data = array(
            'ex_money' => $obj['ex_money'],                                                              // 当前金额
            'ex_level' => $this->getTitle($obj['ex_level']),                                             // 当前等级
            'ex_sub' => $ex_sub,                                                                         // 下级代理数量
            'good' => $good,                                                                             // 今日必推
            'share_money' => sprintf("%.2f", $this->em->get('ex_profit') *  ($good['ex_share'] / 100)),                      // 分享金额
            'share' => 'http://' . $_SERVER['HTTP_HOST'] . '/Phone/Goods/index/id/' . $good['goods_id']. '?member_id='. $this->member_id    // 分享地址
        );

        $this->assign($data);
        $this->display();
    }

    /**
     *  开通收益
     */
    public function profitOpen()
    {
        $eom   = new ExtensionOpenModel();
        $check = I('get.check', 1);

        $list_today  = $eom->getListPerson($this->member_id, 1);
        $list_last   = $eom->getListPerson($this->member_id, 2);

        switch ($check) {
            case 1:
                $list = $list_today;
                break;
            case 2:
                $list = $list_last;
                break;
        }

        $today_money = $this->getMoneyTotal($list_today, 'ex_p_money')->formatMoney();         // 今日金额
        $last_money  = $this->getMoneyTotal($list_last, 'ex_p_money')->formatMoney();           // 历史金额


        $data = array(
            'check' => $check,
            'total' => sprintf("%.2f", $last_money + $today_money),
            'list'  => $list
        );

        $this->assign($data);
        $this->display();
    }

    /**
     *  商品收益
     */
    public function profitGood()
    {
        $egm = new ExtensionGoodModel();

        $check = I('get.check', 1);

        $list_today  = $egm->getListGood($this->member_id, 1);
        $list_last   = $egm->getListGood($this->member_id, 2);

        switch ($check) {
            case 1:
                $list = $list_today;
                break;
            case 2:
                $list = $list_last;
                break;
        }

        $today_money = $this->getMoneyTotal($list_today, 'ex_money')->formatMoney();         // 今日金额
        $last_money  = $this->getMoneyTotal($list_last, 'ex_money')->formatMoney();           // 历史金额

        $data = array(
            'check' => $check,
            'total' => sprintf("%.2f", $last_money + $today_money),
            'list'  => $list
        );

        $this->assign($data);
        $this->display();
    }

    /**
     *  会员热榜
     */
    public function profitMember()
    {
        $m = M('shop_extension_open');
        $list_today = $m->query($this->getSql(1, $this->today()));                 // 今日
        $list_last = $m->query($this->getSql(2, $this->today()));                  // 历史
        $week = $m->query($this->getSql(3, $this->today()));                       // 一周

        $data = array(
            'list_today' => $list_today,
            'list_last' => $list_last,
            'week' => empty($week[0]) ?: null
        );
        $this->assign($data);
        $this->display();
    }




    /**
     *  选择
     */
    public function payCheck()
    {
        $invitation = $this->mm->where(array('member_id' => $this->member_id))->getField('ex_invitation');      // 订单号

        $this->assign('ex_register', $this->em->get('ex_register'));
        $this->assign('platform', $this->platform);
        $this->assign('invitation', $invitation.'-1111-'.rand(1000,9999));
        $this->assign('status', is_weixin());
        $this->display();
    }


    /**
     *  支付
     */
    public function pay()
    {
        $register   = $this->em->get('ex_register');
        switch (I('get.status', 1)) {
            case 1:
                if (is_weixin()) {
                    $this->wechatPhone($register, I('get.invitation'));
                } else {
                    $this->wechatPay($register, I('get.invitation'));
                }

                break;
            case 2:
                $this->aliPay($register, I('get.invitation'));
                break;
        }
    }


    // -------------------------以下控制器函数-------------------------------- //
    public function getTitle($num)  // 代理等级
    {
        switch ($num) {
            case 1:
                return $this->em->get('ex_level_1');
            case 2:
                return $this->em->get('ex_level_2');
            case 3:
                return $this->em->get('ex_level_3');
        }
    }

    public function getMoneyTotal($data, $filed)    // 金额累加
    {
        $count = 0;
        foreach ($data as $v) {
            $count += $v[$filed];
        }
        $this->money = $count;
        return $this;
    }

    public function formatMoney()   // 金额格式化
    {
        return sprintf("%.2f", $this->money);
    }

    public function pullGoodDay()   // 推荐商品
    {
        $gm = new GoodsModel();
        return $gm->where(array('goods_id' => $this->em->get('ex_good_push')))
            ->field('goods_id,goods_name,picture,price,price_market,point,ex_share_num,ex_share')
            ->find();
    }

    public function getShareUrl($code)  // 分享URL
    {
        return 'http://' . $_SERVER['HTTP_HOST'] . '/phone/extension/login?exu_code=' . $code;
    }

    public function getShareCode()  // 分享二维码
    {
        Vendor('phpqrcode.qrlib');
        ob_clean();
        return \QRcode::png($this->getShareUrl($this->mm->find($this->member_id)['ex_invitation']), false, 'L', 4, 1, false);
    }

    public function today() // 今日-历史
    {
        $start_time = strtotime(date("Y-m-d", time()));
        $end_time = $start_time + 60 * 60 * 24;
        return array(date("Y-m-d H:i:s", $start_time), date("Y-m-d H:i:s", $end_time));
    }

    public function getSql($status, $time)  // 会员榜
    {
        switch ($status) {
            case 1:
                $o_sql = "WHERE shop_extension_open.ex_create_time < '" . $time[1] . "' AND " . "shop_extension_open.ex_create_time > '" . $time[0] . "'";
                $g_sql = "WHERE shop_extension_good.ex_create_time < '" . $time[1] . "' AND " . "shop_extension_good.ex_create_time > '" . $time[0] . "'";
                break;
            case 2:
                $o_sql = "WHERE shop_extension_open.ex_create_time < '" . $time[0] . "'";
                $g_sql = "WHERE shop_extension_good.ex_create_time < '" . $time[0] . "'";
                break;
            case 3:
                $value = date("Y-m-d H:i:s", strtotime("-1 week"));
                $o_sql = "WHERE shop_extension_open.ex_create_time > '" . $value . "'";
                $g_sql = "WHERE shop_extension_good.ex_create_time > '" . $value . "'";
                break;
        }

        return 'SELECT
                    `ex_u_id`,
                    `ex_p_id`,
                    sum(ex_p_money) AS total,
                    `ex_create_time`,
                    `nickname`,
                    `phone`
                FROM
                    (
                        SELECT
                            `ex_u_id`,
                            `ex_p_id`,
                            `ex_p_money`,
                            `ex_create_time`
                        FROM
                            `shop_extension_open` ' . $o_sql . '
                       
                        UNION
                            SELECT
                                ex_s_id AS ex_u_id,
                                ex_p_id,
                                ex_money AS ex_p_money,
                                ex_create_time
                            FROM
                                shop_extension_good ' . $g_sql . '
                    ) AS shop_extension_member
                JOIN shop_member ON shop_member.member_id = shop_extension_member.ex_u_id
                GROUP BY
                    ex_p_id
                ORDER BY
                    total DESC';
    }

    public function wechatPay($register, $invitation)  // 微信支付拼接
    {
        vendor('PayWechat.PayNotifyCallBack');
        vendor('PayWechat.Weixin');

        $url        = "https://api.mch.weixin.qq.com/pay/unifiedorder";                                               // 微信地址


        $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $headers[] = 'Connection: Keep-Alive';
        $headers[] = 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3';
        $headers[] = 'Accept-Encoding: gzip, deflate';
        $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0';

        $order_no   = $invitation;
        $appid      = "wx93ac7736b1e564e1";
        $mch_id     = "1523223211";
        $key        = "aasd123qkzf812312451F1asdasdasda";
        $nonce_str  = MD5($order_no);
        $total_fee  = $register * 100;
        $create_ip  = getIP();
        $notify_url = C('WEB_URL').'/Notify/wechatNotify';
        $trade_type = 'MWEB';
        $body       = $this->platform;
        $scene_info = '{"h5_info":{"type":"Wap","wap_url":"' . C('WEB_URL') . '","wap_name":"支付"}}';

        $signA      = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$order_no&scene_info=$scene_info&spbill_create_ip=$create_ip&total_fee=$total_fee&trade_type=$trade_type";
        $strSignTmp = $signA . "&key=$key";
        $sign       = strtoupper(MD5($strSignTmp));
        $post_data  = "<xml><appid>$appid</appid><body>$body</body><mch_id>$mch_id</mch_id><nonce_str>$nonce_str</nonce_str><notify_url>$notify_url</notify_url><out_trade_no>$order_no</out_trade_no><scene_info>$scene_info</scene_info><spbill_create_ip>$create_ip</spbill_create_ip><total_fee>$total_fee</total_fee><trade_type>$trade_type</trade_type><sign>$sign</sign></xml>";
        $dataxml    = $this->http_post($url, $post_data, $headers);
        header("content-type:text/html;charset=utf-8");

        $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($objectxml['return_code'] == 'SUCCESS') {
            echo "<script>window.location='".$objectxml['mweb_url']."'</script>"; exit;
        }
    }

    function http_post($url = '', $post_data = array(), $header = array(), $timeout = 30)   // 微信支付提交
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    function wechatPhone($register, $invitation)  // 手机端微信支付
    {
        $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $headers[] = 'Connection: Keep-Alive';
        $headers[] = 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3';
        $headers[] = 'Accept-Encoding: gzip, deflate';
        $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0';
        $openid  = session('openid');
        $weixin_config = C('weixin_config');
        $userip = get_client_ip();
        $appid  = $weixin_config['APPID'];
        $mch_id = $weixin_config['MCHID'];
        $key    = $weixin_config['KEY'];
        $order_no = $invitation;
        $nonce_str = MD5($invitation);
        $total_fee = $register * 100;
        $spbill_create_ip = $userip;
        $notify_url = C('WEB_URL').'/Notify/wechatNotify';
        $trade_type = 'JSAPI';
        $body = "百宝库商城订单支付";
        $scene_info = '{"h5_info":{"type":"Wap","wap_url":"' . C('WEB_URL') . '","wap_name":"支付"}}';
        $signA = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&openid=$openid&out_trade_no=$order_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
        $strSignTmp = $signA . "&key=$key";
        $sign = strtoupper(MD5($strSignTmp));
        $post_data = "<xml><appid>$appid</appid><body>$body</body><mch_id>$mch_id</mch_id><nonce_str>$nonce_str</nonce_str><notify_url>$notify_url</notify_url><openid>$openid</openid><out_trade_no>$order_no</out_trade_no><scene_info>$scene_info</scene_info><spbill_create_ip>$spbill_create_ip</spbill_create_ip><total_fee>$total_fee</total_fee><trade_type>$trade_type</trade_type><sign>$sign</sign>
  </xml>";
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $dataxml = $this->http_post($url, $post_data, $headers);
        header("content-type:text/html;charset=utf-8");
        $xmlarray  = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data["appId"] = $xmlarray['appid'];
        $data["timeStamp"] = time();
        $data["nonceStr"] = createNoncestr();
        $data["package"] = "prepay_id=".$xmlarray['prepay_id'];
        $data["signType"] = "MD5";
        $singA = 'appId='.$data['appId'].'&nonceStr='.$data['nonceStr'].'&package='.$data['package'].'&signType='.$data['signType'].'&timeStamp='.$data['timeStamp'].'&key='.$weixin_config['KEY'];
        $data['paySign'] = strtoupper(MD5($singA));
        $this->assign('pay_data', json_encode($data));
        $this->display('wechatPhone');
    }


    function aliPay($register, $invitation)   // 支付宝支付
    {
        vendor('Alipay.corefunction');
        vendor('Alipay.md5function');
        vendor('Alipay.notify');
        vendor('Alipay.submit');


        $alipay_config = C('alipay_config');
        /*************************请求参数************************* */
        $payment_type = "1"; //支付类型 //必填，不能修改
        $notify_url = get_host().'/Phone/Notify/aliNotify'; //服务器异步通知页面路径
        $return_url2 = get_host().'/Phone/Extension/pullCoupon'; //页面跳转同步通知页面路径
        $seller_email = $alipay_config['seller_email']; //卖家支付宝帐户必填
        $out_trade_no = $invitation; //商户订单号 通过支付页面的表单进行传递，注意要唯一！
        $subject = $this->platform;  //订单名称 //必填 通过支付页面的表单进行传递
        $total_fee = $register;   //付款金额  //必填 通过支付页面的表单进行传递
        $body = '';  //订单描述 通过支付页面的表单进行传递
        $show_url = '';  //商品展示地址 通过支付页面的表单进行传递
        $anti_phishing_key = ""; //防钓鱼时间戳 //若要使用请调用类文件submit中的query_timestamp函数
        $exter_invoke_ip = get_client_ip(); //客户端的IP地址

        $parameter = array(
            "service" => "alipay.wap.create.direct.pay.by.user",
            //"service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "payment_type" => $payment_type,
            "notify_url" => $notify_url,
            "return_url" => $return_url2,
            "seller_email" => $seller_email,
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
            "total_fee" => $total_fee,
            "body" => $body,
            "show_url" => $show_url,
            "anti_phishing_key" => $anti_phishing_key,
            "exter_invoke_ip" => $exter_invoke_ip,
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );

        //建立请求
        $alipaySubmit = new \Vendor\Alipay\AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "post", "确认");
        echo $html_text;
    }

    public function checkPay()  // 验证支付
    {
        echo $this->mm->find($this->member_id)['ex_level']; exit;
    }

    public function share_add()   // 分享自增
    {
        D('goods')->where(array('goods_id' => I('get.id')))->setInc('ex_share_num',1);
    }
}